package cn.initcap.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author initcap
 * @date 2018/8/10 PM4:38
 */
public class HttpUtil {

    private static final int THREAD_SIZE = 10;
    private static final int THREAD_INLINE_TOTAL = 10;

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = new ThreadPoolExecutor(0, THREAD_SIZE, 60L,
                TimeUnit.SECONDS, new SynchronousQueue<>(), new NameThreadFactory("httpUtil"));
        final CountDownLatch countDownLatch = new CountDownLatch(THREAD_SIZE);
        for (int i = 0; i < THREAD_SIZE; i++) {
            executorService.execute(() -> {
                try {
                    for (int j = 0; j < THREAD_INLINE_TOTAL; j++) {
                        URL url = new URL("http://192.168.220.130/index.html");
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        InputStream in = conn.getInputStream();
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        byte[] buff = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buff)) >= 0) {
                            bout.write(buff, 0, len);
                        }
                        in.close();
                        bout.close();
                        byte[] response = bout.toByteArray();
                        System.out.println(new String(response, "UTF-8"));
                        Thread.sleep(3000);
                    }
                } catch (Exception e) {

                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }
}
